package communication.hall
{
	import com.netease.protobuf.UInt64;
	
	import communication.CertManager;
	import communication.majiang.MajiangMsgSender;
	
	import modules.GameDispatcher;
	import modules.GameEvent;
	import modules.lobby.LobbyEvent;
	
	import protobuf.HSPKG_BROADCAST_NTF;
	import protobuf.HSPKG_CHANGE_AVATAR_ACK;
	import protobuf.HSPKG_CHANGE_SEX_ACK;
	import protobuf.HSPKG_DEL_MAIL_ACK;
	import protobuf.HSPKG_MAIL_COUNT_ACK;
	import protobuf.HSPKG_MAIL_NTF;
	import protobuf.HSPKG_MATCH_JOINED_NTF;
	import protobuf.HSPKG_NAME_NICKNAME_ACK;
	import protobuf.HSPKG_NAME_NICKNAME_NTF;
	import protobuf.HSPKG_NEW_MAIL_NTF;
	import protobuf.HSPKG_OTHERDATA_ACK;
	import protobuf.HSPKG_QUERY_TABLE_INFO_ACK;
	import protobuf.HSPKG_RECORD_ACK;
	import protobuf.HSPKG_SEARCH_RECORD_ACK;
	import protobuf.HSPKG_SELECT_TABLE_ACK;
	import protobuf.HSPKG_TNMT_DETAIL_ACK;
	import protobuf.HSPKG_TNMT_LIST_ACK;
	import protobuf.HSPKG_TNMT_PLAYERLIST_ACK;
	import protobuf.HSPKG_TNMT_REG_PLAYER_ACK;
	import protobuf.HSPKG_TNMT_START_NTF;
	import protobuf.HSPKG_TNMT_TABLELIST_ACK;
	import protobuf.HSPKG_TNMT_UNREG_PLAYER_ACK;
	import protobuf.HSPKG_UPDATE_BALANCE_NTF;
	import protobuf.HSPKG_USER_INFO_NTF;
	import protobuf.PKG_AUTH_ACK;
	import protobuf.PKG_AUTH_CHALLENGE_CMD;
	import protobuf.PLAYING_PLAYER_BRIEF_INFO;
	import protobuf.PKG_AUTH_ACK.E_RESULT_TYPE;
	
	import utils.FloatHandler;

	public final class HallMsgProcesser
	{



		private static var _instance:HallMsgProcesser;

		public static function getInstance():HallMsgProcesser
		{
			if (_instance == null)
			{
				_instance = new HallMsgProcesser();
			}
			return _instance;
		}

		private function get certManager():CertManager
		{
			return CertManager.getInstance();
		}

		/**
		 * 大厅数据发送者
		 */
		private function get hallMsgSender():HallMsgSender
		{
			return HallMsgSender.instance;
		}

		private function get dispatcher():GameDispatcher
		{
			return GameDispatcher.instance;
		}

		/**
		 * 处理
		 * @param pkg
		 * 客户端连接其他游戏服务器(目录服务器，游戏逻辑服务器)时，
		 * 将保存的CLIENT_SESSION_CERT发送到服务端，
		 * 服务端用Login服务器的公钥对其签名进行验证，
		 * 服务器向客户端发送随机挑战码，客户端用其会话私钥对挑战码签名，
		 * 将签名结果发回服务端，服务端用客户端用其会话公钥验证挑战码签名，如果通过则客户端通过身份验证。
		 */
		public function OnRecvAuthChallengeCmd(pkg:PKG_AUTH_CHALLENGE_CMD):void
		{
			logger("接收到大厅挑战码");

			hallMsgSender.sendChallenge(pkg.challengeCode);

		}

		public function OnRecvAuthAck(pkg:PKG_AUTH_ACK):void
		{
			logger("大厅挑战码验证结果");

			var response:PKG_AUTH_ACK = pkg;
			var result:int = response.result;

			switch (result)
			{
				case E_RESULT_TYPE.eSUCCESS:
					logger("通过大厅服务器身份验证");
					break;
				default:
					logger("大厅服务器身份验证失败");
					break;
			}
		}

		/**
		 * 接收桌子列表数据
		 * @param pkg
		 */
		public function OnRecvSelectTableAck(pkg:HSPKG_SELECT_TABLE_ACK):void
		{
			if (pkg.tables.length == 0)
			{
				logger("获取桌子列表数据,共" + pkg.tables.length + "条记录");
			}

			dispatcher.dispatchEvent(new LobbyEvent(LobbyEvent.GET_TABLE_LIST, pkg));
		}

		/**
		 * 通知客户端端没有匿称，需要起一个
		 **/
		public function OnRecvNameNicknameNtf(pkg:HSPKG_NAME_NICKNAME_NTF):void
		{
			logger("通知客户端端没有匿称，需要起一个");
			dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_NAME_NICKNAME_NTF.toString()));
		}

		/**
		 * 起昵称的回应
		 **/
		public function OnRecvNameNicknameAck(pkg:HSPKG_NAME_NICKNAME_ACK):void
		{
			logger("起昵称的回应");
			switch (pkg.errorCode)
			{
				case 0:
					logger("起昵称成功");
					GlobalData.nickname = certManager.convertByteArrayToString(pkg.nickName);
					dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_NAME_NICKNAME_ACK.toString(), {result: 0}));
					break;
				default:
					logger("起昵称失败");
					dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_NAME_NICKNAME_ACK.toString(), {result: 1}));
					break;
			}

		}

		/**
		 * 通知用户信息
		 **/
		public function OnRecvUserInfoNtf(pkg:HSPKG_USER_INFO_NTF):void
		{
			logger("通知用户信息");

			GlobalData.balance = pkg.balance;
			GlobalData.nickname = certManager.convertByteArrayToString(pkg.nickName);
			GlobalData.sex = pkg.sex;
			GlobalData.username = certManager.convertByteArrayToString(pkg.userName);
			var myCurrency:String = certManager.convertByteArrayToString(pkg.currency);
			GlobalData.myCurrency = myCurrency;

			GlobalData.avatarId = Math.max(1, pkg.avatar);

			GlobalData.myVPP = pkg.vpp;

			dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_USER_INFO_NTF.toString()));
		}

		/**
		 * 回应用户更改性别
		 **/
		public function OnRecvChangeSexAck(pkg:HSPKG_CHANGE_SEX_ACK):void
		{
			logger("回应用户更改性别");
			switch (pkg.errorCode)
			{
				case 0:
					logger("更改性别成功");
					GlobalData.sex = pkg.sex;
					dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_CHANGE_SEX_ACK.toString()));
					break;
				default:
					logger("更改性别失败");
					break;

			}
		}

		/**
		 * 回应用户更改头像
		 **/
		public function OnRecvChangeAvatarAck(pkg:HSPKG_CHANGE_AVATAR_ACK):void
		{
			switch (pkg.errorCode)
			{
				case 0:
					logger("用户更改头像成功");
					GlobalData.avatarId = pkg.avatar;
					dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_CHANGE_AVATAR_ACK.toString()));
					break;
				default:
					logger("用户更改头像失败");
					break;
			}
		}

		/**
		 * 通知玩家所在的桌子列表
		 **/
		public function OnRecvMatchJoinedNtf(pkg:HSPKG_MATCH_JOINED_NTF):void
		{
			logger("通知玩家所在的桌子列表");
			var tableIds:Array = pkg.tableId;
			if (tableIds.length > 0)
			{
				if (MajiangMsgSender.instance)
				{
					for each (var tableId:UInt64 in tableIds)
					{
						MajiangMsgSender.instance.enterTable(tableId);
					}
				}
				else
				{
					MajiangMsgSender.waitEnterTableIds = tableIds;
				}
			}
			else
			{
				logger("玩家所在桌子列表为空！");
			}
		}

		/**
		 * 获取锦标赛列表数据
		 */
		public function OnRecvTnmtListAck(pkg:HSPKG_TNMT_LIST_ACK):void
		{
			if (pkg.tnmtInfos.length == 0)
			{
				logger("获取锦标赛列表数据,共" + pkg.tnmtInfos.length + "条记录");
			}
			dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_TNMT_LIST_ACK.toString(), pkg));
		}

		/**
		 * 接收锦标赛详细信息
		 */
		public function OnRecvTnmtDetailAck(pkg:HSPKG_TNMT_DETAIL_ACK):void
		{
			/*logger("接受锦标赛详细信息 ");
			var startTime:int = getTimer();
			var tournamentDetailModel:TournamentDetailModel = LobbyDataModel.getTournamentDetailById(pkg.tournamentId);

			//更新锦标赛的基本信息
			var tournament:TournamentModel = LobbyDataModel.getTournamentById(pkg.tournamentId);
			tournament.update(pkg.detail);

			tournamentDetailModel.totalChips = pkg.totalChips;
			tournamentDetailModel.minChips = pkg.minChips;
			tournamentDetailModel.maxChips = pkg.maxChips;
			tournamentDetailModel.averageChips = int(pkg.averageChips);

			tournamentDetailModel.blinds = pkg.blinds;
			tournamentDetailModel.bonus = pkg.bonus;
			tournamentDetailModel.describe = pkg.describe;
			tournamentDetailModel.runningtime = pkg.runningtime;
			tournamentDetailModel.totalBonus = pkg.totalBonus;

			dispatcher.dispatchEvent(new LobbyEvent(LobbyEvent.UPDATE_TOURNAMENTINFO));

			logger("接受锦标赛详细信息处理时长：" + (getTimer() - startTime));*/
		}

		/**
		 * 接收锦标赛玩家列表
		 */
		public function OnRecvTnmtPlayerlistAck(pkg:HSPKG_TNMT_PLAYERLIST_ACK):void
		{
			/*logger("接收锦标赛玩家列表:pkg.firstRank:" + pkg.firstRank + ",pkg.startpos:" + pkg.startpos + ",pkg.totalplayer:" + pkg.totalplayer + ",pkg.playerlist.length:" + pkg.playerlist.length);

			//计算玩家排名排名
			function computeRank(playerlist:Array, firstRank:int, startPos:int):void
			{
				var length:int = playerlist.length;
				var currentPlayerInfo:TNMT_PLAYER_INFO;
				for (var i:int = 0; i < length; i++)
				{
					currentPlayerInfo = playerlist[i];
					currentPlayerInfo.rank += firstRank;
				}
			}

			var startTime:int = getTimer();
			var tournamentDetailModel:TournamentDetailModel = LobbyDataModel.getTournamentDetailById(pkg.tournamentId);

			tournamentDetailModel.startpos = pkg.startpos;
			tournamentDetailModel.totalplayer = pkg.totalplayer;
			tournamentDetailModel.playerlist = pkg.playerlist;

			tournamentDetailModel.playerRank = pkg.playerRank;

			computeRank(pkg.playerlist, pkg.firstRank, tournamentDetailModel.startpos);

			dispatcher.dispatchEvent(new LobbyEvent(LobbyEvent.UPDATE_TOURNAMENT_PLAYERLIST));
			logger("接收锦标赛玩家列表处理时长：" + (getTimer() - startTime));*/
		}

		/**
		 * 接收某锦标赛桌子列表
		 */
		public function OnRecvTnmtTablelistAck(pkg:HSPKG_TNMT_TABLELIST_ACK):void
		{
			/*logger("接收某锦标赛桌子列表 ");

			var tournamentDetailModel:TournamentDetailModel = LobbyDataModel.getTournamentDetailById(pkg.tournamentId);

			tournamentDetailModel.tablepage = pkg.page;
			tournamentDetailModel.tables = pkg.tables;

			dispatcher.dispatchEvent(new LobbyEvent(LobbyEvent.UPDATE_TOURNAMENT_TABLELIST, pkg));*/
		}

		/**
		 * 接收注册锦标赛回复
		 */
		public function OnRecvTnmtRegPlayerAck(pkg:HSPKG_TNMT_REG_PLAYER_ACK):void
		{
			/*logger("接收注册锦标赛回复");

			var tournament:TournamentModel = LobbyDataModel.getTournamentById(pkg.tournamentId);
			if (pkg.bSuc)
			{
				tournament.isRegister = true;
			}

			dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_TNMT_REG_PLAYER_ACK.toString()));*/
		}

		/**
		 * 接收移除注册锦标赛报名回复
		 */
		public function OnRecvTnmtUnRegPlayerAck(pkg:HSPKG_TNMT_UNREG_PLAYER_ACK):void
		{
			/*logger("接收移除注册锦标赛报名回复");

			var tournament:TournamentModel = LobbyDataModel.getTournamentById(pkg.tournamentId);
			if (pkg.bSuc)
			{
				tournament.isRegister = false;
			}

			dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_TNMT_UNREG_PLAYER_ACK.toString()));*/

		}

		/**
		 * 锦标赛开始，通知客户端进入锦标赛
		 */
		public function OnRecvTnmtStartNtf(pkg:HSPKG_TNMT_START_NTF):void
		{
			logger("锦标赛开始，通知客户端进入锦标赛");

			var tableId:UInt64 = pkg.tableid;

			var ip:String = certManager.convertByteArrayToString(pkg.ip);
			var port:uint = pkg.port;
			dispatcher.dispatchEvent(new LobbyEvent(LobbyEvent.ADD_TABLEID_ADDRESS, {tableId: tableId, ip: ip, port: port}));

			if (MajiangMsgSender.instance)
			{
				MajiangMsgSender.instance.enterTable(tableId);
			}
			else
			{
				MajiangMsgSender.waitEnterTableIds = [tableId];
			}
		}

		/**
		 * 接收(其他数据)服务器时间、在线人数、在座玩家数
		 */
		public function OnRecvOtherDataAck(pkg:HSPKG_OTHERDATA_ACK):void
		{
			var time:int = pkg.time;
			var online:int = pkg.online;
			var sitNum:int = pkg.sitNum;

			GlobalData.serverTime = time;
			GlobalData.online = online;
			GlobalData.sitNum = sitNum;

		}

		/**
		 * 通知客户端更新玩家钱
		 */
		public function OnRecvUpdateBalenceAck(pkg:HSPKG_UPDATE_BALANCE_NTF):void
		{
			GlobalData.balance = pkg.balance;
		}

		/**
		 * 公告
		 */
		public function OnRecvBroadcastNtf(pkg:HSPKG_BROADCAST_NTF):void
		{
			/*var content:String = pkg.content.readUTFBytes(pkg.content.length);
			UIAllRefer.instance.lobbyUI.noticeLabel.text = content;

			UIAllRefer.instance.lobbyUI.showRollMessage(content);*/
		}

		/**
		 * 收到邮件
		 */
		public function OnRecvMailNtf(pkg:HSPKG_MAIL_NTF):void
		{
			/*var arr:Array = [];
			for (var i:int = 0, len:int = pkg.mailList.length; i < len; i++)
			{
				arr.push({id: pkg.mailList[i].id, time: pkg.mailList[i].time, content: pkg.mailList[i].content, state: pkg.mailList[i].state, label: "系统邮件"});
			}
			UIAllRefer.instance.mailUI.setSrcArrayCollection(new ArrayCollection([arr]));*/
		}

		/**
		 * 请求删除邮件返回
		 */
		public function OnRecvDelMailAck(pkg:HSPKG_DEL_MAIL_ACK):void
		{
		}

		/**
		 * 请求邮件数量返回
		 */
		public function OnRecvMailCountAck(pkg:HSPKG_MAIL_COUNT_ACK):void
		{
			/*trace(pkg.count);
			UIAllRefer.instance.lobbyUI.playerInfoView.msgCount.text = String(pkg.count);*/
			dispatcher.dispatchEvent(new GameEvent(HSProto.HSID_MAIL_COUNT_ACK.toString(),pkg.count));
		}

		/**
		 * 当前桌玩家信息返回
		 */
		public function OnRecvQueryTableInfoAck(pkg:HSPKG_QUERY_TABLE_INFO_ACK):void
		{
			var tableId:UInt64 = pkg.tableId;
			var arr:Array = [];
//			var cuccry:String = LobbyDataModel.selectedCashTable.currency;
			for each (var object:PLAYING_PLAYER_BRIEF_INFO in pkg.players)
			{
				arr.push({userName: certManager.convertByteArrayToString(object.playerName), chips: FloatHandler.TwoFormatToString(object.chips), rank: 0});
			}
			dispatcher.dispatchEvent(new LobbyEvent(LobbyEvent.SHOW_PLAYER_INFO_LIST,arr));
		}

		/** 接受回放数据 */
		public function OnRecvRecordAck(pkg:HSPKG_RECORD_ACK):void
		{
			trace("接受回放数据");
			dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_RECORD_ACK.toString(), pkg));
		}

		/** 接受到回放查询数据 */
		public function OnRecvSearchRecordAck(pkg:HSPKG_SEARCH_RECORD_ACK):void
		{
			trace("接受到回放查询数据");
			dispatcher.dispatchEvent(new LobbyEvent(HSProto.HSID_SEARCH_RECORD_ACK.toString(), pkg));
		}

		public function OnRecvNewMailNtf(pkg:HSPKG_NEW_MAIL_NTF):void
		{

		}
	}
}
